<template>
	<div>
		<el-upload ref="uploadRef" v-model:file-list="state.fileList" :http-request="handelRequest"
			list-type="picture-card" :limit="maxCount" :show-file-list="!isAvatar">
			<img v-if="isAvatar && state.fileList.length > 0" :src="state.fileList[0].url" class="avatar" />
			<el-icon v-else class="avatar-uploader-icon">
				<Plus />
			</el-icon>
		</el-upload>
	</div>
</template>

<script setup>

import { onMounted, reactive, ref, watch } from 'vue';
import http from "@/utils/request";
import OSS from 'ali-oss';
import utils from '../../utils/utils';

const props = defineProps({
	accept: {
		type: String,
		default: "image"
	},
	maxCount: {
		type: Number,
		default: 9
	},
	autoUpload: {
		type: Boolean,
		default: false
	},
	file: {
		type: Array,
		default: []
	},
	isAvatar: {
		type: Boolean,
		default: false
	}
})

const state = reactive({
	RegionId: '',
	OSSAccessKeyId: '',
	AccessKeySecret: '',
	securityToken: '',
	RoleSessionName: '',
	fileList: props.file
})

let uploadRef = ref(null);

onMounted(() => {
	initOssInfo();
})

function initOssInfo() {
	http.get("/api/AliCloud/getAuth").then(res => {
		state.RegionId = res.result.RegionId;
		state.OSSAccessKeyId = res.result.AccessKeyId;
		state.AccessKeySecret = res.result.AccessKeySecret;
		state.securityToken = res.result.Credentials.SecurityToken;
		state.RoleSessionName = res.result.RoleSessionName;
	})
}

function handelRequest(e) {
	let client = new OSS({
		bucket: state.RoleSessionName,
		region: state.RegionId,
		accessKeyId: state.OSSAccessKeyId,
		accessKeySecret: state.AccessKeySecret,
		secure: true,
		headers: {
			'Content-Type': 'image/jpg'
		}
	});

	let fileList = state.fileList;

	let data = new Date();
	let Y = data.getFullYear();
	let M = (data.getMonth() + 1);
	let D = data.getDate();

	fileList.forEach((item, index) => {
		if (item.raw) {
			let fileName = Y + '/' + M + '/' + utils.randomString() + '.' + item.name.split('.')[1];

			client.put(fileName, item.raw).then(res => {

				if (props.isAvatar) {
					state.fileList = [];
				}

				state.fileList.push(res);

				uploadRef.value.clearFiles();  // 上传成功后清空上传信息数据
			}).catch(err => {
				console.log(err)
			});
		}
	})
}

defineExpose({
	state
})

</script>

<style lang="scss" scoped>
.avatar {
	width: 148px;
	height: 148px;
	display: block;
}
</style>
